import json

import rasa.utils.io
import typing
from rasa.nlu import utils
from typing import NoReturn, Text, Dict, Any

if typing.TYPE_CHECKING:
    from rasa.nlu.training_data import TrainingData

"""
    主要定义：接口基础类
        （1）训练数据阅读器接口类
        （2）训练数据写入器接口类（markdown）
        （3）字符串转json接口类
"""


class TrainingDataReader:
    """训练数据阅读器接口类"""

    def read(self, filename: Text, **kwargs: Any) -> "TrainingData":
        """从文件中读取TrainingData"""
        return self.reads(rasa.utils.io.read_file(filename), **kwargs)

    def reads(self, s: Text, **kwargs: Any) -> "TrainingData":
        """从字符串读取TrainingData"""
        raise NotImplementedError


class TrainingDataWriter:
    """训练数据写入器接口：将markdown格式的TrainingData对象写入文件"""

    def dump(self, filename: Text, training_data) -> None:
        """Writes a TrainingData object in markdown format to a file."""
        s = self.dumps(training_data)
        utils.write_to_file(filename, s)

    def dumps(self, training_data: "TrainingData") -> Text:
        """Turns TrainingData into a string."""
        raise NotImplementedError


class JsonTrainingDataReader(TrainingDataReader):
    """字符串转json接口：将字符串转换为json对象并继续传递"""

    def reads(self, s: Text, **kwargs: Any) -> "TrainingData":
        """Transforms string into json object and passes it on."""
        js = json.loads(s)
        return self.read_from_json(js, **kwargs)

    def read_from_json(self, js: Dict[Text, Any], **kwargs: Any) -> "TrainingData":
        """Reads TrainingData from a json object."""
        raise NotImplementedError
